package com.shanzhe.eshop.common.nio;

import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Author yinwei
 * @create 2021/12/25
 * @Version 1.0
 */
public class SocketServer {

    public static void main(String[] args) throws Exception{
        ServerSocket serverSocket = new ServerSocket(9000);

        while (true){
            Socket socket = serverSocket.accept();
            Worker worker = new Worker(socket);
            worker.start();
        }
    }

   static class Worker extends Thread {

        Socket socket;

        public Worker(Socket socket){
            this.socket = socket;
        }

        @Override
        public void run() {
            try {
                //tcp三次握手建立连接成功

                //socket的输入流相当于就是不停的读取人家通过tcp协议发送过来的一个个的tcp包
                //把tcp包的数据通过IO输入流提供给你
                InputStreamReader in = new InputStreamReader(socket.getInputStream());
                OutputStream out = socket.getOutputStream();

                char[] buf = new char[1024 * 1024];
                //通过IO输入流读取的方式将tcp包的数据读取出来放入jvm的缓冲数组中
                int len = in.read(buf);

                while (len!=-1){
                    String request = new String(buf,0,len);
                    System.out.println("服务端接受到了请求"+Thread.currentThread().getName()+request);
                    //这个意思是说 通过IO流发送响应数据回去 此时在底层就会把响应的数据拆分成tcp包回传回去
                    out.write("服务响应数据请求成功".getBytes());

                    //需要不停的读取socket流传输过来的数据 因为buf才1kb可能才读取流中1kb的数据后面可能还有很多数据所以需要不停的读取
                    len = in.read(buf);
                }

                out.close();
                in.close();
                socket.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }


    }
}
